<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 原生产品
 * @author www.dingwei.cn
 */
class Products extends MY_Controller {
	
	const PRODUCT_DEUBG = FALSE;//参数调试输出log
	/**
	 * 商家模型
	 * @var MerchantUserModel
	 */
	public $mMerchant;
	
	/**
	 * 分类模型
	 * @var ConsumerCategoryModel
	 */
	public $mCategory;
	
	/**
	 * 评论模型
	 * @var MerchantCommentModel
	 */
	public $mComment;
	
	/**
	 * 产品模型
	 * @var ConsumerProductModel
	 */
	public $mProduct;
	
	/**
	 * 订单模型
	 * @var ConsumerOrderModel
	 */
	public $mOrder;
	
	/**
	 * 支付模型
	 * @var ConsumerPayModel
	 */
	public $mPay;
	
	/**
	 * 购物车模型
	 * @var ConsumerCartModel
	 */
	public $mCart;
	
	/**
	 * 活动模型
	 * @var ConsumerPromotionModel
	 */
	public $mPromotion;
	
	/**
	 * 活动模型
	 * @var MerchantPromotionModel
	 */
	public $mMerPromotion;
	
	/**
	 * 地址模型
	 * @var ConsumerAddressModel
	 */
	public $mAddress;
	
	/**
	 * 
	 * @var ConsumerMessageModel
	 */
	public $mMsg;
    /**
     *
     * @var MerchantMessageModel
     */
	public $mMerMsg;

    /**
     * @var DlnOrderModel
     */
	public $mDln;

    /**
     * @var ConsumerPostalCardModel
     */
    public $mPostcard;
	public function __construct(){
		parent::__construct();
		$this->loadModel('ConsumerCategoryModel', 'mCategory', 'consumer');

		$this->loadModel('ConsumerProductModel', 'mProduct', 'consumer');
		$this->loadModel('ConsumerCartModel', 'mCart', 'consumer');
	}

    /**
     * 获取商品规格 标签
     */
	public function productVariant(){
        //表单验证
        $vConf = array(
            array('product_id', '产品id', 'required|is_natural_no_zero'),
        );

        $this->formDataValidation($vConf);

        $productId = post('product_id');

        //获取产品
        $tA = $this->mProduct->getInfo($productId, 0, true);
        if ( ! $tA){
            $this->appReturn(0,'产品不存在');
        }

        $tData = [];
        $tA['icon'] = getImage($tA['icon']);
        $tData['info'] = $tA;
        //获取产品属性
        $tData['property'] = $this->mProduct->getPropertyList($productId);

        //获取变体
        $tData['variant'] = $this->mProduct->getPropertyVariantList($productId);
        //获取属性
        $tData['tags'] = $this->mProduct->getTagsList($productId);

        $this->appReturn(1,'获取成功',$tData);
    }

    /**
     * 预览订单
     */
    public function checkout(){
        $this->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
        $this->loadModel('ConsumerPostalCardModel', 'mPostcard', 'consumer');
        $this->loadModel('MerchantPromotionModel', 'mMerPromotion', 'merchant');
        $this->loadModel('ConsumerPromotionModel', 'mPromotion','consumer');
        $this->loadModel('AdmSettingModel', 'mSett', 'admin');

        //表单验证
        $vConf = array(
            array('merchant_id', '商家id', 'required|is_natural_no_zero'),
            array('cart_id', '购物车id', 'required'),
            array('address_id', '收货地址id', 'is_natural_no_zero'),
        );

        $this->formDataValidation($vConf);

        $merchantId = post('merchant_id');
        $addressId = post('address_id');
        $cartIds = trim(post('cart_id'));

        //验证商家信息/状态
        $merchant = $this->mMerchant->getInfoByIds(array($merchantId));

        if(!isset($merchant[$merchantId])){
            $this->appReturn(0, '商家不存在');
        }
//        p($merchant);
        if($merchant[$merchantId]['status'] != 2){
            $this->appReturn(0, '商家不存在或已禁用');
        }

        if($merchant[$merchantId]['business'] != 2){
            $this->appReturn(0, '商家休息中~');
        }

        /**----------------------------------
         * 获取商家多段时间[单个商家]
         */
        $tTime = $this->mMerchant->getBusinessTimeList($merchantId);
        $week_s = ['','周一','周二','周三','周四','周五','周六','周日'];
        $week_str = explode(',', $merchant[$merchantId]['business_week']);
        $tWeek = array();
        foreach ($week_str as $kk=>$vv){
            if ($vv){
                $tWeek[] = $week_s[$vv];

            }
        }
        $_time = [];
        foreach ($tTime as $t){
            $_time[] = [
                'business_time_start' => time_to_second($t['business_time_start']),
                'business_time_end' => time_to_second($t['business_time_end']),
            ];
        }

        $_for = getCustomConfig('expect_take_time');
        $_other = $this->mSett->get('rob_expect_time', 'deliveryman');
        //预计到达时间组
        $arriveTime = appArriveTime($_time,$_for,$_other,$merchant[$merchantId]['expect_arrive_time'],20);
        $self_lifting_time = appArriveTime($_time,$_for,0,0,20);
        //店铺信息
        $shop = array(
            'shop_name' => $merchant[$merchantId]['shop_name'],
            'portrait' => $merchant[$merchantId]['portrait'],
            'mobile' => $merchant[$merchantId]['store_tel'],
            'latitude' => $merchant[$merchantId]['latitude'],
            'longitude' => $merchant[$merchantId]['longitude'],
            'address' => $merchant[$merchantId]['address'],
            'able_use_coupon' => $merchant[$merchantId]['able_use_coupon'],
            'able_cash_coupon' => $merchant[$merchantId]['able_cash_coupon'],
            'shop_type' => $merchant[$merchantId]['shop_type'],
            'time' => $tTime,
            'week' => $tWeek?implode(',', $tWeek):'周一,周二,周三,周四,周五,周六,周日',
        );

        //购物车商品
        $cartIds = explode(',', $cartIds);
        $this->db->select('c.quantity ,c.tags, c.product_id, c.variant_id')
                ->join($this->mProduct->tbProduct.' p', 'p.id = c.product_id')
                ->where('consumer_id', $this->userId)
                ->where_in('c.id', $cartIds);
        $products = $this->mProduct->getAll($this->mProduct->tbCart.' c');

        if(!$products){
            $this->appReturn(0, '商品不存在');
        }

        $pData = [];
        $cartData = [];//购物车商品信息

        foreach ($products as $p){
            $pData[] = [
                'product_id' => $p['product_id'],
                'sort' => $p['variant_id'],
                'tags' => $p['tags'],
                'quantity' => $p['quantity'],
            ];
            $p['variant_id'] = $p['variant_id']?$p['variant_id']:0;

            $cartData[$p['product_id'].'_'.$p['variant_id']] = $p;

        }
        /**----------------------------------------------------------------
         * 验证产品参数
         * 备注：获取数据库中，按商品 以及商品规格的正确性
         * @var Ambiguous $tProduct
         */
        $tProduct = $this->mProduct->canAddOrder($this->userId, $pData);
        if ( ! is_array($tProduct)){
            $msg = (is_string($tProduct) ? $tProduct : '格式错误');
            if(!(strpos($msg,'下架') === false)){
                $exData = explode('-', $msg);
                $this->appReturn(-1, substr($exData[1],0,-1).'已下架，请重新选购',(object)array());
            }else{
                $this->appReturn(0, $msg);
            }
        }

        $normalAmount = 0;//正价商品总价
        $totalWeight = 0; //商品重量
        $tempData = [];//商品信息
        $lunch_box = 0;//餐盒费
        $totalFee = 0;//商品总价
        $isSpecial = 1;//会员专属
        foreach ($tProduct as $k=>&$v){
            $v['variant_id'] = $v['variant_id']?$v['variant_id']:0;
            $str =  $v['id'].'_'.$v['variant_id'];
            $number = isset($cartData[$str])?$cartData[$str]['quantity']:0;
            if($number == 0){
                $this->appReturn(0, '购买数量错误');
            }
            $tempData[] = [
                'merchant_id' => $merchantId,
                'name' => $v['name'],
                'number' => $number,
                'is_special' => $v['is_special'],
                'icon' => getImage($v['icon']),
                'goods_price' => $v['goods_price'],
                'market_price' => $v['market_price'],
                'property' => !empty($v['property'])?implode(',', json_decode($v['property'], true)):'',
                'tags' => !empty($v['tags'])?implode(',',array_filter(explode('|', $v['tags']))):'',
            ];
            $normalAmount += $v['goods_price']*$number;
//            if($v['discount'] == 0){
//                $normalAmount += $v['goods_price']*$number;
//            }
            if($v['is_special'] == 2){
                $isSpecial = 2;
            }
            $totalWeight += $v['weight']*$number;
            $lunch_box += $v['lunch_box_fee'];
            $totalFee += $v['goods_price']*$number;
        }

        //验证起送价
        if($merchant[$merchantId]['min_consume'] > 0 && $merchant[$merchantId]['min_consume'] > $totalFee){
            $this->appReturn(0, $merchant[$merchantId]['min_consume'].'起送');
        }
        //批量获取商户满减劵
        $tFullCut = $this->mMerPromotion->getFullCutListByMerchantIds(array($merchantId));
        //根据商家 与订单金额 获取满减额度
        $fullcut = array('money'=>0,'max_money'=>0);
        if ($tFullCut && $normalAmount){
            $fullcut = $this->mMerPromotion->getSatisfyFullCut($tFullCut[$merchantId]['rule'], $normalAmount); //商品的总价
        }
        /**
         * 获取首单减免
         */
        $tFirstOrder = $this->_firstOrder(array($merchantId));

        //首单减免
        $firstOrder = 0;
        if (isset($tFirstOrder[$merchantId]) && ! empty($tFirstOrder[$merchantId]) && $normalAmount){
            $firstOrder = $tFirstOrder[$merchantId];
        }

        /**
         * 红包【单个商家】
         */
        $tBonus = array();
        if($isSpecial == 1 && $normalAmount > 0){
            $tBonus = $this->mPromotion->appGetBonusLogList($this->userId,1,1,false,$normalAmount);
        }

        /**
         * 代金券[单个商家]
         */
        $tCoupon = $normalAmount>0?$this->mPromotion->appGetCouponLogList($this->userId,1,1,false,$normalAmount,$merchantId):array();

        //获取包邮卡减免配送
        $tPostalCard = $this->mPostcard->appGetBonusLogList($this->userId,1,1,false,true,true);

        /**---------------------------------------------
         * 多商品运费筛选
         * 备注：逻辑为，如果该商家的商品中，有一个为包邮，则不需要在寻找邮费。如果不是就赋值运费，运费的来源是商品的总质量+地区计算得来
         */

        if(!$addressId){
            $this->loadModel('ConsumerAddressModel', 'mAddress','consumer');
            $Address = $this->mAddress->getDefaultAddress($this->userId, $merchant[$merchantId]['latitude'], $merchant[$merchantId]['longitude']);

            if ( ! is_array($Address)){
                $Address = (array)$Address;
            }
            $addressId = empty($Address['id'])?0:$Address['id'];
        }
        $tmAmount = $this->shippingFee($addressId, $totalWeight, $merchant[$merchantId]['latitude'], $merchant[$merchantId]['longitude']);
        //是否在店铺营业时间内
        $tBusiness = $this->mMerchant->getBusinessMerchant(array($merchantId));
        $data = [
            'merchant_id' => $merchantId,
            'is_business'=>isset($tBusiness[$merchantId]) ? 2:1,
            'shop' => $shop,
            'products' => $tempData,
            'fullcut' => $fullcut,
            'firstOrder' => $firstOrder,
            'tBonus' => $tBonus,
            'tCoupon' => $tCoupon,
            'postCard' => $tPostalCard,
            'address' => $Address,
            'is_special' => $isSpecial,
            'shippingFee' => $tmAmount,
            'lunch_box_fee' => $lunch_box,
            'goods_amount' => $totalFee,
            'shortage_handing' => $this->mOrder->getShortage(),
            'expect_arrive_time' => $arriveTime,
            'self_lifting_time' => $self_lifting_time,

        ];
        $this->appReturn(1, '', $data);
    }

    /**
     * 提交订单
     */
    public function done(){

        $this->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
        $this->loadModel('ConsumerPostalCardModel', 'mPostcard', 'consumer');
        $this->loadModel('MerchantPromotionModel', 'mMerPromotion', 'merchant');
        $this->loadModel('ConsumerPromotionModel', 'mPromotion','consumer');
        $this->loadModel('ConsumerAddressModel', 'mAddress','consumer');
        $this->loadModel('AdmSettingModel', 'mSett', 'admin');

        //表单验证
        $vConf = array(
            array('merchant_id', '商家id', 'required|is_natural_no_zero'),
            array('cart_id', '购物车id', 'required'),
            array('address_id', '收货地址id', 'is_numeric'),
            array('postal_card_id', '包邮卡id', 'is_numeric'),
            array('bonus_id', '红包id', 'required'),
            array('coupon_id', '代金券id', 'required'),
            array('expense_type', '消费模式', 'required|in_list[1,2]'),
            array('expect_arrive_time', '预计送达时间', 'required'),
        );

        $this->formDataValidation($vConf);

        $merchantId = post('merchant_id');
        $addressId = post('address_id');
        $bonusId = post('bonus_id');
        $couponId = post('coupon_id');
        $postalCardId = post('postal_card_id');
        $expense_type = post('expense_type');
        $cartIds = trim(post('cart_id'));
        $remark = trim(post('remark'));
        $shortage = trim(post('shortage'));
        $expect_arrive_time = trim(post('expect_arrive_time'));

        if(!$addressId && $expense_type == 1){
            $this->appReturn(0, '请选择收货地址');
        }

        if(!is_numeric(strtotime($expect_arrive_time))){
            $this->appReturn(0, '预计送达时间格式错误');
        }
        //验证商家信息/状态
        $merchant = $this->mMerchant->getInfoByIds(array($merchantId));
        if(!$merchant[$merchantId]){
            $this->appReturn(0, '商家不存在');
        }

        if($merchant[$merchantId]['status'] != 2){
            $this->appReturn(0, '商家不存在或已禁用');
        }

        if($merchant[$merchantId]['business'] != 2){
            $this->appReturn(0, '商家休息中~');
        }

        //购物车商品
        $cartIds = array_filter(explode(',', $cartIds));
        $this->db->select('c.quantity ,c.tags, c.product_id, c.variant_id')
            ->join($this->mProduct->tbProduct.' p', 'p.id = c.product_id')
            ->where('consumer_id', $this->userId)
            ->where_in('c.id', $cartIds);
        $products = $this->mProduct->getAll($this->mProduct->tbCart.' c');

        if(!$products){
            $this->appReturn(0, '商品不存在');
        }

        $pData = [];
        $cartData = [];//购物车商品信息
        $cartProduct = [];
        foreach ($products as $p){
            $pData[] = [
                'product_id' => $p['product_id'],
                'sort' => $p['variant_id'],
                'tags' => $p['tags'],
                'quantity' => $p['quantity'],
            ];
            $p['variant_id'] = $p['variant_id']?$p['variant_id']:0;

            $cartData[$p['product_id'].'_'.$p['variant_id']] = $p;
            $cartProduct = [
                'consumer_id' => $this->userId,
                'product_id' => $p['product_id'],
                'variant_id' => $p['variant_id'],
            ];

        }
        /**----------------------------------------------------------------
         * 验证产品参数
         * 备注：获取数据库中，按商品 以及商品规格的正确性
         * @var Ambiguous $tProduct
         */
        $tProduct = $this->mProduct->canAddOrder($this->userId, $pData);
        if ( ! is_array($tProduct)){
            $this->appReturn(0,(is_string($tProduct) ? $tProduct : '格式错误'));
        }

        $normalAmount = 0;//正价商品总价
        $totalWeight = 0; //商品重量
        $lunch_box = 0;//餐盒费
        $productAmount = 0;//商品总价
        foreach ($tProduct as $k=>&$v){
            $v['variant_id'] = $v['variant_id']?$v['variant_id']:0;
            $str =  $v['id'].'_'.$v['variant_id'];
            $number = isset($cartData[$str])?$cartData[$str]['quantity']:0;
            if($number == 0){
                $this->appReturn(0, '购买数量错误');
            }
            $normalAmount += $v['goods_price']*$number;
//            if($v['discount'] == 0){
//                $normalAmount += $v['goods_price']*$number;
//            }
            $v['weight'] = $v['variant_id'] > 0?$v['v_weight']:$v['weight'];
            $totalWeight += $v['weight']*$number;
            $lunch_box += $v['lunch_box_fee'];
            $productAmount += $v['goods_price']*$number;
        }


        /**----------------------------------------------------------------
         * 获取收货地址
         */
        $shippingFee = 0;
        $tAddress = [
            'consignee' => '',
            'gender' => '',
            'mobile' => '',
            'address_desc' => '',
            'latitude' => '',
            'longitude' => '',
            'province' => '',
            'city' => '',
            'county' => '',
        ];
        if($expense_type == 1){
            //送货上门
            $tAddress = $this->mAddress->getInfo($addressId,$this->userId);
            if(!$tAddress){
                $this->appReturn(0, '地址不存在');
            }
            $tmAmount = $this->shippingFee($addressId, $totalWeight, $merchant[$merchantId]['latitude'], $merchant[$merchantId]['longitude']);

            $shippingFee = $tmAmount['shipping_fee'];
        }


        $totalAmount = $productAmount + $lunch_box + $shippingFee;
        $reality_amount = $totalAmount;

        /**-----------------------------------------------------------------------------------
         * 订单数据 保存订单
         */

        /**-------------------------------------------------------------
         * 促销
         */
        $tBonus = $this->mPromotion->getBonusByIds(array($bonusId),$this->userId);
        //红包
        $bonus = 0;
        if (isset($tBonus[$bonusId])){
            $bonus = $tBonus[$bonusId]['money'];
            /*if ($normalAmount <= $bonus){
                $this->appReturn(0,'总消费太少了，结果让红包都抵完了');
            }*/
            $reality_amount = $reality_amount - $bonus;
        }
        //代金劵
        $tCoupon = $this->mPromotion->getCouponByIds(array($couponId),$this->userId);
        $coupon = 0;
        if (isset($tCoupon[$couponId])){
            $coupon = $tCoupon[$couponId]['money'];
            /*if ( $normalAmount <= $coupon){
                $this->appReturn(0,'总消费太少了，结果让代金劵都抵完了');
            }*/
            $reality_amount = $reality_amount - $coupon;
        }
        /**
         * 批量获取商家的满减劵规则
         */
        $tFullCut = $this->mMerPromotion->getFullCutListByMerchantIds(array($merchantId));
        $fullcut = array('money'=>0,'max_money'=>0);
        if ($tFullCut){
            $fullcut = $this->mMerPromotion->getSatisfyFullCut($tFullCut[$merchantId]['rule'], $normalAmount);
            if (!is_numeric($fullcut['money'])){
                $this->appReturn(0,'满减金额好像有变动,请重新下单');
            }
            $reality_amount = $reality_amount - $fullcut['money'];//实际支付金额 减去满减劵
        }

        /**
         * 获取首单减免
         */
        $tFirstOrder = $this->_firstOrder(array($merchantId));
        $firstOrder = 0;
        if (isset($tFirstOrder[$merchantId]) && ! empty($tFirstOrder[$merchantId]) && $normalAmount){
            $reality_amount = $reality_amount - $tFirstOrder[$merchantId];
            $firstOrder = $tFirstOrder[$merchantId];
        }
        // 获取包邮卡
        $postalCard = 0;
        $tPostalCard = array();
        if(!empty($postalCardId)) {
            $tPostalCard = $this->mPostcard->getInfoIds(array($postalCardId), $this->userId);
            $postalCard = isset($tPostalCard[$postalCardId])?$tPostalCard[$postalCardId]['money']:0;
            $sf = $shippingFee - $postalCard;
            $sf = $sf < 0 ? $shippingFee : $postalCard;
            $reality_amount = $reality_amount - $sf;
            $postalCard = $sf;
        }


        /*收益 start*/

        $web_percent =isset($tMerchant[$merchantId]['percent'])?$tMerchant[$merchantId]['percent']:'0';
        $webservice = round($productAmount*$web_percent/100, 2); //平台服务费
        $min_order_web_amount = isset($tMerchant[$merchantId]['min_order_web_amount'])?$tMerchant[$merchantId]['min_order_web_amount']:'0';//保底抽成

        if($webservice < $min_order_web_amount){
            $webservice = $min_order_web_amount;
        }
        $merchantIncome = $reality_amount - $shippingFee - $webservice + $bonus;//商家收入
        if($merchantIncome <= 0){
            $webIncome = $reality_amount - $shippingFee;
        }else{
            $webIncome = $webservice - $bonus; //平台收入
        }
        $deliverymanIncome = $shippingFee;//配送员收入

        if (isset($merchant[$merchantId]['shipping_type']) && $merchant[$merchantId]['shipping_type'] == 1){
            //商家配送
            $merchantIncome += $shippingFee;
            $deliverymanIncome = 0;
        }
        /*收益 end*/
        //送达时间

        $expectTakeTime = getCustomConfig('expect_take_time'); // 商家接单时间
        $robExpectTime = $this->mSett->get('rob_expect_time', 'deliveryman'); // 配送员接单时间

        $expectArriveTime = strtotime($expect_arrive_time);
        $firstArriveTime = time() + ($expectTakeTime + $merchant[$merchantId]['expect_arrive_time'] + $robExpectTime) * 60;

        if($expectArriveTime < $firstArriveTime){
            $expectArriveTime = $firstArriveTime;
        }
        if(strtotime(date('Y-m-d', $expectArriveTime)) < strtotime(date('Y-m-d'))){
            $this->appReturn(0, '预计送达时间有误');
        }
        if(!$shortage){
            $shortage = '{"value":"","remark":""}';
        }
        //订单状态
        $status = 1;
        if($reality_amount == 0){
            $status = $expense_type == 1? 2:3;
        }

        $order = [
            'merchant_id' => $merchantId,
            'consumer_id' => $this->userId,
            'code' => getOrderCode(),
            'pay_code' => getOrderCode(),
            'type' => $merchant[$merchantId]['category_id'],
            'expense_type' => $expense_type,
            'pay_type' => $reality_amount>0 ? 0:1,
            'pay_time' => $reality_amount>0 ? '':time(),
            'product_amount' => $productAmount,
            'total_amount' => $totalAmount,
            'reality_amount' => $reality_amount,
            'remark' => $remark,
            'status' => $status,
            'contacts' => $tAddress['consignee'],
            'gender' => $tAddress['gender'],
            'mobile' => $tAddress['mobile'],
            'address' => $tAddress['address_desc'],
            'latitude' => $tAddress['latitude'],
            'longitude' => $tAddress['longitude'],
            'province_id' => $tAddress['province'],
            'city_id' => $tAddress['city'],
            'county_id' => $tAddress['county'],
            'shipping_fee' => $shippingFee,
            'percent' => $web_percent,
            'bonus' => $bonus,
            'lunch_box_fee' => $lunch_box,
            'postal_card' => $postalCard ,
            'merchant_discount'=> sprintf("%.2f", $fullcut['money'] + $firstOrder + $coupon),
            'param' => json_encode(array(
                'coupon' => $coupon,
                'bonus' => $bonus,
                'full_cut' => $fullcut['money'],
                'first_order_reduce' => $firstOrder,
                'postal_card' => $postalCard,
                'lunch_box_fee' => $lunch_box,
            )),
            'addtime' => time(),
            'deliveryman_income' => $deliverymanIncome,
            'merchant_income' => $merchantIncome,
            'web_income' => $webIncome,
            'after_sale' => 1,//未申请
            'is_comment' => 1,//未评价
            'shipping_type' => $merchant[$merchantId]['shipping_type'],//配送模式 根据该商家来设置的
            'shortage_handing' => $shortage,//{"value":"s1","remark":"备注信息"}
            'expect_arrive_time' => $expectArriveTime,

        ];

        $this->db->trans_begin();//开启事务

        if ( ! $tId = $this->mOrder->save($order)){
            $this->db->trans_rollback();
            $this->appReturn(0,'下单失败');
        }

        /**--------------------------------------------------------------
         * 组合 订单产品信息
         */
        $orderProduct = [];
        $orderProductAmount = 0;//商品总价
        foreach ($tProduct as $key=>$value){
            $str =  $value['id'].'_'.$value['variant_id'];
            $number = isset($cartData[$str])?$cartData[$str]['quantity']:0;
            if($number == 0){
                $this->appReturn(0, '购买数量错误');
            }

            $orderProduct[] = [
                'order_id' => $tId,
                'product_id' => $value['id'],
                'price' => $value['goods_price'],
                'quantity' => $number,
                'reality_amount' => sprintf('%.2f',$value['goods_price']*$number),
                'variant_id' => $value['variant_id'],
                'tags' => empty($value['tags'])?"":$value['tags'],
            ];
            $orderProductAmount = $value['goods_price']*$number + $orderProductAmount;
        }
        if(sprintf('%.2f', $orderProductAmount) != sprintf('%.2f', $productAmount)){
            $this->db->trans_rollback();
            $this->appReturn(0,'商品价格出现变动,请重新下单');
        }
        if(count($orderProduct) != count($cartIds)){
            $this->db->trans_rollback();
            $this->appReturn(0,'下单失败');
        }

        //批量保存订单产品信息
        if ( ! $this->mOrder->saveOrderProduct($orderProduct)){
            $this->db->trans_rollback();
            $this->appReturn(0,'下单失败');
        }

        //处理包邮卡
        if (!empty($postalCardId) && !empty($tPostalCard)){
            $this->db->where('id', $postalCardId);
            $query = $this->mPostcard->update($this->mPostcard->tbPostalCardLog,
                array(
                    'status'=>2,
                    'order_id' => $tId,
                    'usedtime' => time()
                )
            );
            if ( !$query){
                $this->db->trans_rollback();
                $this->appReturn(0,'下单失败');
            }
        }

        /**
         * 下单成功后，处理红包，处理代金劵 处理购物车
         */
        $this->loadModel('ConsumerPromotionModel', 'mPromotion','consumer');
        if ( ! $this->mPromotion->saveBatchBonusLog(array('status'=>2), array($bonusId))){
            $this->db->trans_rollback();
            $this->appReturn(0,'下单失败');
        }

        if ( ! $this->mPromotion->saveBatchCouponLog(array('status'=>2), array($couponId))){
            $this->db->trans_rollback();
            $this->appReturn(0,'下单失败');
        }

        //订单下单时 减少库存
        $reduce_stock = $this->mSett->get('reduce_stock');
        if ($reduce_stock == 1){
            //下单时减少
            $result = $this->mOrder->reduceStocks($tId);
            if($result['status'] == 0){
                $this->db->trans_rollback();
                $this->appReturn(0, $result['message']);
            }
        }

        /**
         * 删除购物车商品
         */
        $this->db->where_in('id', $cartIds);
        if ( ! $this->mCart->delete($this->mCart->tbShoppingCart)){
            $this->db->trans_rollback();
            $this->appReturn(0,'下单失败');
        }

        /**
         * 获取支付参数
         */
        $tData = array(
            'code'=> $order['code'],//预支付订单
            'total_amount'=>sprintf('%.2f', $reality_amount),
        );

        $this->db->trans_commit();
        $this->appReturn(1,'订单提交成功',$tData);
    }


    /**
     * 获取店铺首单减免金额
     * @param array $merchantIds 商家ids数组
     * @return array 商家为键的数组 ["1"=>10]
     */
    private function _firstOrder($merchantIds){
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
        //获取店铺订单数量
        $tA = $this->mOrder->firstOrderByMerchantId($merchantIds, $this->userId);

        $data = array();
        foreach ($tA as $v){
            if($v['count'] == 0 && $v['first_order_reduce'] > 0){
                $data[$v['merchant_id']] = $v['first_order_reduce'];
            }
        }

        return $data;
    }

    /**
     * 根据所选地址，获取运费
     * @param number $addressId
     */
    private function shippingFee($address_id= 0, $weight = 0, $latitude = '', $longitude = ''){

        //加载模型
        $this->loadModel('ConsumerAddressModel', 'mAddress','consumer');
        $this->loadModel('DlnOrderModel', 'mDln','deliveryman');
        $this->loadModel('AdmSettingModel', 'mSett', 'admin');

        $config = $this->mSett->get('base_distribution_fee,base_distribution_distance,exceed_base_distance,
                                    exceed_base_distance_number,base_distribution_weight,exceed_base_weight,
                                    exceed_base_weight_number','deliveryman');

        //获取用户地址所在地
        $tAddress = $this->mAddress->getInfo($address_id,$this->userId);
        $distance = 0;
        $weight_amount = 0;
        $distance_amount = 0;
        $expect = 0;
        $expectW = 0;
        if($tAddress){
            //获取商家接单范围
//            $merchant_distance_limit = $this->mSett->get('merchant_distance_limit');
            //计算距离(米)
            $distance =  getDistance($latitude, $longitude, $tAddress['latitude'], $tAddress['longitude']);

//            if($distance > $merchant_distance_limit*1000){
//                $this->appReturn(0,'不在商家配送范围内~');
//            }


            //运费数据
            $expect = (($distance / 1000) - $config['base_distribution_distance']);//超出距离 km
            if($expect <= 0){
                $expect = 0;
            }

            if($config['exceed_base_distance_number'] > 0){
                $distance_amount = (ceil($expect / $config['exceed_base_distance_number']) * $config['exceed_base_distance']);
            }
            $expectW = $weight - $config['base_distribution_weight'];
            if($expectW <= 0){
                $expectW = 0;
            }

            if($config['base_distribution_weight'] > 0 && $weight > $config['base_distribution_weight']){
                $weight_amount += (ceil($expectW / $config['exceed_base_weight_number']) * $config['exceed_base_weight']);
            }
        }


        $tData = array(
            'shipping_fee'=>sprintf('%.2f',$this->mDln->getIncome($distance/1000,ceil($weight))),
            'base_amount'=>sprintf('%.2f',$config['base_distribution_fee']),//基础邮费
            'base_weight'=>sprintf('%.2f',$config['base_distribution_weight']),//基础重量
            'distance'=>sprintf('%.2f',$distance),//距离
            'weight'=>sprintf('%.2f',$weight),//总重量
            'distance_amount'=> sprintf('%.2f',$distance_amount),//超出距离/费用
            'weight_amount'=> sprintf('%.2f',$weight_amount),//超出重量/费用
            'exceed_distance'=>sprintf('%.2f',$expect * 1000),//超出距离
            'exceed_weight'=>sprintf('%.2f',$expectW),//超出重量
            'is_free_shipping'=>1,
        );

        return $tData;
    }

}